package com.lagou.boot;

import com.lagou.handler.UserServiceHandler;
import com.lagou.serializer.JSONSerializer;
import com.lagou.serializer.RpcDecoder;
import com.lagou.serializer.RpcEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

public class ServerBoot {

    // 创建一个方法启动服务器
    public static void startServer(String ip,int port) throws Exception {
        // 创建2个线程池对象
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        // 创建服务器启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        // 设置服务器启动引导类对象
        serverBootstrap.group(boosGroup,workGroup)
                // 设置通道为NIO
                .channel(NioServerSocketChannel.class)
                // 创建监听器
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        // 获取通道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        // 设置编码
                        pipeline.addLast(new RpcEncoder(Object.class, new JSONSerializer()));
                        pipeline.addLast(new RpcDecoder(Object.class, new JSONSerializer()));
//                        pipeline.addFirst(new StringEncoder());
//                        pipeline.addLast(new StringDecoder());
                        // 自定义ChannelHandler对象
                        pipeline.addLast(new UserServiceHandler());
                    }
                });

        serverBootstrap.bind(ip, port).sync();
        // 将IP及端口信息自动注册到Zookeeper
        registeredZookeeper(ip, port);
    }

    private static void registeredZookeeper(String ip,int port) throws Exception {
        // 定义重载策略
        RetryPolicy exponentialBackoffRetry = new ExponentialBackoffRetry(1000, 3);

        CuratorFramework client = CuratorFrameworkFactory.builder()
                // 连接地址
                .connectString("121.4.48.59:2181")
                // 会话超时时间
                .sessionTimeoutMs(1000)
                // 连接超时时间
                .connectionTimeoutMs(3000)
                // 重载策略
                .retryPolicy(exponentialBackoffRetry)
                // 独立命名空间
                .namespace("netty")
                .build();

        client.start();

        // 将netty发热ip和端口信息放入节点
        String path = "/"+ip+":"+port;

        client.create().creatingParentContainersIfNeeded()
                .withMode(CreateMode.EPHEMERAL).forPath(path,("01").getBytes());

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        Stat stat = new Stat();
                        System.out.println(new String(client.getData().storingStatIn(stat).forPath(path)));
                        client.setData().withVersion(stat.getVersion()).forPath(path, String.valueOf(System.currentTimeMillis()).getBytes());
                        Thread.sleep(5000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();

    }
}
